package org.ysling.litemall.core.service;
// Copyright (c) [ysling] [927069313@qq.com]
// [litemall-plus] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//             http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
import org.ysling.litemall.core.util.NotifyMessageUtil;
import org.ysling.litemall.db.domain.*;
import org.ysling.litemall.db.util.GrouponConstant;
import org.ysling.litemall.db.util.OrderConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ysling.litemall.db.service.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderCoreService {

    @Resource
    private LitemallOrderService orderService;
    @Resource
    private LitemallUserService userService;
    @Resource
    private SubscribeMessageService subscribeMessageService;
    @Resource
    private QCodeService qCodeService;
    @Resource
    private LitemallGrouponRulesService grouponRulesService;
    @Resource
    private LitemallGrouponService grouponService;
    @Resource
    private LitemallOrderGoodsService orderGoodsService;
    @Resource
    private NotifyService notifyService;
    @Resource
    private LitemallBrandService brandService;

    /**
     * 修改团购状态和订单状态
     * @param groupon
     */
    public synchronized void updateGrouponStatus(LitemallGroupon groupon){
        //获取团购规则信息
        LitemallGrouponRules grouponRules = grouponRulesService.findById(groupon.getRulesId());
        //仅当发起者才创建分享图片
        if (groupon.getGrouponId() == 0) {
            String goodsName = grouponRules.getGoodsName();
            String picUrl = grouponRules.getPicUrl();
            String url = qCodeService.createGrouponShareImage(goodsName, picUrl, groupon);
            groupon.setShareUrl(url);
        }

        //获取团购参与信息
        List<LitemallGroupon> grouponList = grouponService.queryJoinRecord(groupon.getGrouponId());
        if (groupon.getGrouponId() != 0 && (grouponList.size() >= grouponRules.getDiscountMember() - 1)) {
            //修改当前用户的团购信息
            LitemallGroupon grouponSource = grouponService.queryById(groupon.getGrouponId());
            this.updateStatus(grouponSource);
            //修改前面已经参与者团购状态
            for (LitemallGroupon grouponActivity : grouponList) {
                this.updateStatus(grouponActivity);
            }
        }else {
            //修改团购状态
            groupon.setStatus(GrouponConstant.STATUS_ON);
            if ( grouponService.updateVersionSelective(groupon) == 0) {
                throw new RuntimeException("更新团购信息失败");
            }

            //修改订单团购状态
            LitemallOrder order = orderService.findById(groupon.getOrderId());
            order.setOrderStatus(OrderConstant.STATUS_GROUPON_ON);
            if (orderService.updateSelective(order) == 0) {
                throw new RuntimeException("更新团购订单信息失败");
            }
        }
    }

    /**
     * 修改团购和订单状态，并发送通知邮件
     * @param grouponActivity
     */
    private void updateStatus(LitemallGroupon grouponActivity){
        grouponActivity.setStatus(GrouponConstant.STATUS_SUCCEED);
        if (grouponService.updateVersionSelective(grouponActivity) == 0) {
            throw new RuntimeException("更新团购信息失败");
        }

        //修改订单团购状态
        LitemallOrder order = orderService.findById(grouponActivity.getOrderId());
        order.setOrderStatus(OrderConstant.STATUS_GROUPON_SUCCEED);
        if (orderService.updateSelective(order) == 0) {
            throw new RuntimeException("更新团购订单信息失败");
        }

        //给商家发送通知
        this.orderNotify(order);
    }


    /**
     * 订单消息通知
     * @param order
     */
    public void orderNotify(LitemallOrder order){
        //获取订单商品
        List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(order.getId());
        for (LitemallOrderGoods orderGoods :orderGoodsList) {
            LitemallBrand brand = brandService.findById(order.getBrandId());
            //新订单订阅通知
            LitemallUser user = userService.findById(brand.getUserId());
            if (brand.getUserId() != null && user != null){
                subscribeMessageService.newOrderSubscribe(user.getWeixinOpenid(),order,orderGoods);
            }
            //店铺邮箱通知
            String orderMessage = NotifyMessageUtil.orderMessage(order, orderGoods);
            if (brand.getMail() != null && !brand.getMail().equals("")){
                notifyService.notifyMail("新订单通知", orderMessage,brand.getMail());
            }else {
                notifyService.notifyMail("新订单通知", orderMessage);
            }
        }
    }

}
